<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
    function __construct()
    {
        parent::__construct();
        $this->M_use = M('User');
    }

    public function index(){
        include './wechat.class.php';
        $options = array(
            'token'=>'e9faf8p271948fe38o4f1d09be01bc9c', //填写你设定的key
            'encodingaeskey'=>'Lf5rN5vsjkSU8pKXmaBtlCjJ2EH6uGKzFg5bn1sIHWz', //填写加密用的EncodingAESKey，如接口为明文模式可忽略
            'appid'=>'wxbf7dc98a302e40a3', //填写高级调用功能的app id
            'appsecret'=>'f84658e605f3f6ad2a2aec3e24b6713f' //填写高级调用功能的密钥D
        );
        $weObj = new \Wechat($options);
        //创建菜单
        $menu = array (
            'button' => array (
                0 => array (
                    'name' => '关于我们',
                    'sub_button' => array (
                        0 => array (
                            'type' => 'click',
                            'name' => '最新消息',
                            'key' => 'news',
                        ),
                        1 => array (
                            'type' => 'click',
                            'name' => '视频介绍',
                            'key' => 'shipin',
                        ),
                        2 => array (
                            'type' => 'click',
                            'name' => '简介',
                            'key' => 'jianjie',
                        ),
                    ),
                ),
                1 => array (
                    'type' => 'click',
                    'name' => '联系客服',
                    'key' => 'connect'
                ),
                2 => array (
                    'name' => '官网',
                    'sub_button' => array (
                        0 => array (
                            'type' => 'view',
                            'name' => '登录',
                            'url' => 'http://meatfinder.com',
                        ),
                        1 => array (
                            'type' => 'view',
                            'name' => '客户注册',
                            'url' => 'https://meatfinder.com/Home/CadastroHome?IdCadastro=2',
                        ),
                        2 => array (
                            'type' => 'view',
                            'name' => '进入官网',
                            'url' => 'http://meatfinder.com',
                        ),
                    ),
                ),
            ),
        );
        $weObj->createMenu($menu);
        //$weObj->valid();//明文或兼容模式可以在接口验证通过后注释此句，但加密模式一定不能注释，否则会验证失败

        $type1 = $weObj->getRev()->getRevType();
        $type = $weObj->getRev()->getRevEvent();
        $data= $weObj->getRev()->getRevData();
        $keyword = $data['Content'];
        $open_id = $data['FromUserName'];
        //获取点击事件触发的内容
        if($type['event'] == 'CLICK'){
            if($type['key'] == 'news'){
                $data =array(
                    "0"=>array(
                        'Title'=>'巴西在世界牛肉和鸡肉市场的参与',
                        'Description'=>"巴西在世界牛肉和鸡肉市场的参与占有突出的地位",
                        'PicUrl'=>'http://mmbiz.qpic.cn/mmbiz_jpg/34COKoG9tPAqSHHqvsteQcicg2reib5DibCeABjsODEbwAHArv8CwKBPPEVQ88lMJ1ibmfeHQASZ9lug3vWZbePgpQ/0?wx_fmt=jpeg',
                        'Url'=>'http://mp.weixin.qq.com/s?__biz=MzI5ODc5NDUyMw==&mid=100000008&idx=1&sn=8ac1acffb34768c03f6468f17a92b957&chksm=6ca12a7c5bd6a36ad775591041e51028d536ad3acd52e5ea89df6aa1274d8ecbd1a1dc3304e8#rd'
                    ),
                );
                $weObj->news($data)->reply();
            }elseif($type['key'] == 'connect'){
                $where['openid'] = $open_id;
                $save['is_login'] = 1;
                $login =$this->M_use->where($where)->save($save);
                if($login!==false){
                    $weObj->text('欢迎来到MeatFinder肉类定位器
请回答数字选择
1  无MeatFinder肉类定位器账号
2  有MeatFinder肉类定位器账号')->reply();
                }
            }elseif($type['key'] == 'shipin'){
                $mediaid='ukaozw9ItnkDTZKQ5Ez28z295UD8QWr7mNLEAt8vMt8';
                $title='MeatFinder 肉类定位器';
                $description='';
                $weObj->video($mediaid,$title,$description)->reply();
            }elseif($type['key'] == 'jianjie'){
                $data =array(
                    "0"=>array(
                        'Title'=>'MeatFinder',
                        'Description'=>"这里，您可以得到最可靠的供应商为您提供的最优惠动物蛋白的报价",
                        'PicUrl'=>'http://mmbiz.qpic.cn/mmbiz_jpg/34COKoG9tPAqSHHqvsteQcicg2reib5DibCgSicAnXbRltuuGH2na6JzPysIuPQHu3M34ibMco2z5ypxKSGicJf7jy9w/0?wx_fmt=jpeg',
                        'Url'=>'http://mp.weixin.qq.com/s?__biz=MzI5ODc5NDUyMw==&mid=100000002&idx=1&sn=3f3a9c92596034b7e5c0d1e1f4bc2999&chksm=6ca12a765bd6a36020522c081024f92b1a7391eb1b46d7a4e5caf9961c00990b5867b21decf8#rd'
                    ),
                );
                $weObj->news($data)->reply();
            }
        }
        //关注公众号后用户信息入库
        if($type['event'] == 'subscribe'){
            $user['openid'] = $data['FromUserName'];
            $detail = $weObj->getUserInfo($data['FromUserName']);
            $user['nickname'] = $detail['nickname'];
            $user['headimgurl']=$detail['headimgurl'];
            M('user')->add($user);
            $weObj->text('欢迎关注MeatFinder肉类定位器')->reply();
        }
        //取消关注删除用户信息
        if($type['event'] == 'unsubscribe'){
            $unsub_id = $data['FromUserName'];
            M('user')->where("openid='$unsub_id'")->delete();
        }

        switch($type1) {
            case \Wechat::MSGTYPE_TEXT :
                if ($keyword == '绑定客服') {
                    $kf_openid = $data['FromUserName'];
                    $ke = M('user')->where("openid='$kf_openid'")->field('user_id')->find();
                    if ($ke) {
                        $kf['user_id'] = $ke['user_id'];
                        $kf['status'] = 1;
                        $kf['is_login'] = 1;
                        M('user')->save($kf);
                        $weObj->text('你已绑定为客服')->reply();
                    } else {
                        $user['openid'] = $data['FromUserName'];
                        $detail = $weObj->getUserInfo($data['FromUserName']);
                        $user['nickname'] = $detail['nickname'];
                        $user['headimgurl'] = $detail['headimgurl'];
                        $user['status'] = 1;
                        $user['is_login'] = 1;
                        M('user')->add($user);
                        $weObj->text('你已绑定为客服')->reply();
                    }
                }

                if($keyword == '取消绑定客服'){
                    $save3['status'] = 0;
                    $save3['is_login'] = 0;
                    $quxiao = $this->M_use->where("openid='$open_id'")->save($save3);
                    if($quxiao){
                        $weObj->text('你已取消绑定客服')->reply();
                    }
                }

                $where1['openid'] = $open_id;//回复者id
                $is_login = $this->M_use->field('is_login,status')->where($where1)->find();

                //输入1时的回复
                if($keyword == 1 && $is_login['is_login'] == 1 && $is_login['status'] != 1){
                    //查询空闲客服的openid
                    $where['status'] = 1;
                    $where['free'] = '0';
                    $ke_data = M('user')->field('openid,nickname,user_id')->where($where)->find();
                    if (!$ke_data) {
                        $weObj->text('客服正忙,请稍后再试!')->reply();die;
                    }
                    $o = $ke_data['openid'];//客服id
                    $nickname = $ke_data['nickname'];
                    $chat_id = $ke_data['user_id'];

                    //此处为客户回复
                    $where2['openid'] = $open_id;
                    $save['free'] = $o;
                    $this->M_use->where($where2)->save($save);
                    $OpenID = $open_id;
                    $txt['touser'] = $OpenID;
                    $txt['msgtype'] = 'text';
                    $txt['text'] = array('content' => "您好，我是客服【" . $nickname . "】，很高兴为您服务。");
                    $result = $weObj->sendCustomMessage($txt);

                    //此处客服回复
                    $where3['openid'] = $o;
                    $save1['free'] = $open_id;
                    $this->M_use->where($where3)->save($save1);
                    $txt['touser'] = $o;
                    $txt['msgtype'] = 'text';
                    $txt['text'] = array('content' => 'New client - no account.');
                    $result = $weObj->sendCustomMessage($txt);
                }

                //输入2时的回复
                if($keyword == 2 && $is_login['is_login'] == 1 && $is_login['status'] != 1){
                    //此处为客户回复
                    $where['status'] = 1;
                    $where['free'] = '0';
                    $ke_data = M('user')->field('openid,nickname,user_id')->where($where)->find();
                    if (!$ke_data) {
                        $weObj->text('客服正忙,请稍后再试!')->reply();die;
                    }
                    $o = $ke_data['openid'];//客服id
                    $where2['openid'] = $open_id;
                    $save['free'] = $o;
                    $this->M_use->where($where2)->save($save);
                    $where3['openid'] = $o;
                    $save1['free'] = $open_id;
                    $this->M_use->where($where3)->save($save1);
                    $OpenID = $open_id;
                    $txt['touser'] = $OpenID;
                    $txt['msgtype'] = 'text';
                    $txt['text'] = array('content' => "请输入MeatFinder肉类定位器账号(手机号码)");
                    $result = $weObj->sendCustomMessage($txt);
                }

                //回复手机号码
                if( isset($keyword{8}) && preg_match("/^\d*$/",$keyword) && $is_login['is_login'] == 1 && $is_login['status'] != 1 ){
                    $user_info ='客人信息';
                    $wher['openid'] = $open_id;
                    $save2['user_info'] = $user_info;
                    $this->M_use->where($wher)->save($save2);
                    $ok_request = M('User')->where($wher)->find();
                    $txt['touser'] = $ok_request['free'];
                    $txt['msgtype'] = 'text';
                    $txt['text'] = array('content'=>$user_info);
                    $result = $weObj->sendCustomMessage($txt);

                    $wh['openid'] = $ok_request['free'];
                    $kefu_open = $this->M_use->where($wh)->find();
                    $nickname = $kefu_open['nickname'];
                    $txt['touser'] = $open_id;
                    $txt['msgtype'] = 'text';
                    $txt['text'] = array('content'=>"您好，我是客服【". $nickname ."】，很高兴为您服务。");
                    $result = $weObj->sendCustomMessage($txt);die;
                }

                //客服与客人对话
                if($keyword!=1 && $keyword!=2 && $keyword!='会话结束' && $is_login['is_login'] == 1){
                    $where4['openid'] = $open_id;
                    $ok_request = M('User')->where($where4)->find();
                    $txt['touser'] = $ok_request['free'];
                    $txt['msgtype'] = 'text';
                    $txt['text'] = array('content'=>$keyword);
                    $result = $weObj->sendCustomMessage($txt);

                    //对聊天记录进行入库
                    $chat_user_open = $data['FromUserName'];
                    $chat_user = M('user')->where("openid='$chat_user_open'")->field('user_id,status')->find();
                    if($chat_user['status'] != 1){
                        //此处为用户
                        $chat['user_id'] = $chat_user['user_id'];
                        $chat['talk_content'] = $keyword;
                        $chat['talk_time'] = time();
                        M('Chat')->add($chat);
                    }else{
                        //此处为客服
                        $chat['reply_user_id'] = $chat_user['user_id'];
                        $chat['talk_content'] = $keyword;
                        $chat['talk_time'] = time();
                        M('Chat')->add($chat);
                    }
                }

                if($keyword == '会话结束' && $is_login['is_login'] == 1){
                    $user_end = $this->M_use->where("openid = '".$open_id."'")->find();
                    if($user_end['status'] == 1){
                        $txt['touser'] = $user_end['free'];
                        $txt['msgtype'] = 'text';
                        $txt['text'] = array('content'=>'本次会话已结束,欢迎下次咨询!');
                        $result = $weObj->sendCustomMessage($txt);
                    }else{
                        $txt['touser'] = $user_end['openid'];
                        $txt['msgtype'] = 'text';
                        $txt['text'] = array('content'=>'本次会话已结束,欢迎下次咨询!');
                        $result = $weObj->sendCustomMessage($txt);
                    }
                    $where5['openid'] = $open_id;
                    $save['reply_time'] = time();
                    $save['free'] = '0';
                    M('user')->where($where5)->save($save);
                    $where6['free'] = $open_id;
                    $save1['free'] = '0';
                    $save1['is_login'] = 0;
                    M('User')->where($where6)->save($save1);
                }
                break;
            case \Wechat::MSGTYPE_EVENT:
                $weObj->text('欢迎回来')->reply();
                break;
            case \Wechat::MSGTYPE_IMAGE:
                break;
            case \Wechat::MSGTYPE_VOICE:
                $weObj->voice()->reply();
                break;
            case \Wechat::MSGTYPE_LOCATION:
                $weObj->text('这么巧,你也在这里啊')->reply();
                break;
            default:
                $weObj->text("help info")->reply();
        }
        file_put_contents('text.txt',print_r($type,true));
    }
    //输出字符串
    public function curl($keyword)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, 'http://meatfinder.com:7003/WeChat?api=customer&phone='.$keyword);
        $response = curl_exec($ch);
        if($response === FALSE){
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $response;
    }

    public function test()
    {
        $ok_request = M('User')->where("openid='oG5yfxMPf0UIB1NcdbOa0IVn_o5U'")->find();
        p($ok_request);
        $key = '13928833633';
        if(isset($key{8}) && preg_match("/^\d*$/",$key)){
            echo 12345;die;
        }else{
            echo 456;die;
        }
        $ccc = $this->curl($key);
        echo $ccc;die;
        $where = 'status = 1 ';
        $where .= "and (free=0 or reply_time+1800 < ".time().")";
        $ke_data = M('user')->where($where)->field('openid,nickname,user_id')->select();
        p($ke_data);
        $url='http://meatfinder.com:7003/WeChat?api=customer&phone=8613928833633';
        // 建立CURL连线
        $ch = curl_init();
        $timeout = 5;
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $file_contents = curl_exec($ch);
        curl_close($ch);
        echo $file_contents;




//        if(intval($aStatus["http_code"])==200){
//            return $sContent;
//        }else{
//            return false;
//        }

        include './wechat.class.php';
        $options = array(
            'token'=>'e9faf8p271948fe38o4f1d09be01bc9c', //填写你设定的key
            'encodingaeskey'=>'Lf5rN5vsjkSU8pKXmaBtlCjJ2EH6uGKzFg5bn1sIHWz', //填写加密用的EncodingAESKey，如接口为明文模式可忽略
            'appid'=>'wxbf7dc98a302e40a3', //填写高级调用功能的app id
            'appsecret'=>'f84658e605f3f6ad2a2aec3e24b6713f' //填写高级调用功能的密钥D
        );
        $weObj = new \Wechat($options);
        $type = $weObj->getRev()->getRevEvent();
        if($type['event'] == 'subscribe'){

        }
        $where = 'status = 1 ';
//        $where .= "and reply_time+1800 < ".time();
        $ke_data = M('user')->where($where)->field('openid,nickname')->select();
        if(!$ke_data){
            $weObj->text('客服正忙,请稍后再试!')->reply();
        }
        foreach($ke_data as $key){
            $kefu_open = $key;
        }
        $o = $kefu_open['openid'];
        $nickname = $kefu_open['nickname'];
    }
}


